package com.desheng.bigdata.ds.queue;

import java.util.Iterator;

/**
 * @Description 队列的自我实现
 *  特点：先进后出，或者后进先出，LIFO
 * @Author deshenglijun
 * @Date 2020/5/17 20:33
 * @Version 1.0
 */
public class Queue<E> implements Iterable<E> {

    private int size;

    private Node<E> head;//最后一个节点

    private class Node<E> {
        E data;
        Node<E> next;

        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }
    }

    public Queue() {
        head = new Node<E>(null, null);
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void enqueue(E e) {
        Node<E> node = head.next;
        if(node == null) {
            head.next = new Node<>(e, null);
        } else {
            while (node.next != null) {
                node = node.next;
            }
            node.next = new Node<>(e, null);
        }
        size++;
    }

    public E dequeue() {
        if(isEmpty()) {
            return null;
        }
        Node<E> old = head.next;
        head.next = old.next;
        size--;
        return old.data;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            @Override
            public boolean hasNext() {
                return size > 0;
            }

            @Override
            public E next() {
                Node<E> next = head.next;
                head.next = next.next;
                size--;
                return next.data;
            }
        };
    }

}
